package com.topten.dao.especificos;

import javax.persistence.TypedQuery;

import com.topten.basicas.seguranca.Usuario;
import com.topten.dao.generico.DAOGenerico;
import com.topten.exceptions.LoginInvalidoException;

public class DAOUsuario extends DAOGenerico<Usuario> implements IDAOUsuario {

	@Override
	public Usuario fazerLogin(String login, String senha)
			throws LoginInvalidoException {
		
		try {
			
			TypedQuery<Usuario> query = entityManager.createNamedQuery("fazerLogin", Usuario.class);
			query.setParameter("log", login);
			query.setParameter("sen", senha);
			return query.getSingleResult();
			
		} catch (Exception e) {
		
			e.printStackTrace();
			throw new LoginInvalidoException("login/senha incorretos");
			
		}
		
	
	}
	
	/*public Usuario efetuarLogin(String login, String senha) throws LoginInvalidoException{
		try {
			TypedQuery<Usuario> query = getEntityManager().createNamedQuery("efetuarLogin", Usuario.class);
			query.setParameter("log", login);
			query.setParameter("sen", senha);
			return query.getSingleResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new LoginInvalidoException();
		}
*/
	

	public Usuario buscarUsuarioPorLogin(String login){
		try{
			this.entityManager.getTransaction().begin();
			TypedQuery<Usuario> query = entityManager.createQuery("select u from Usuario u where u.login=:log", Usuario.class);
			query.setParameter("log",login);
			
			this.entityManager.getTransaction().commit();
			return query.getSingleResult();
		
		}catch(Exception ex){
			ex.printStackTrace();
			if(this.entityManager.getTransaction() != null && this.entityManager.getTransaction().isActive()){
				this.entityManager.getTransaction().rollback();
			}
		}
		return null;		
	}
}
